import type { Router } from 'vue-router'
import type { Menu as MenuData } from '@/api'
import Menu from './Menu'
import Page from './Page'

export default class Menus {
  private _menus: Map<string, Menu> = new Map();
  private _loadedPages: Map<string, Page> = new Map();

  getLoadedPage(name: string) {
    return this._loadedPages.get(name)
  }

  add(menu: Menu) {
    this._menus.set(menu.name, menu)
    return this
  }

  update(router: Router, menus: MenuData[]) {
    // 删除已组册路由
    this._loadedPages.forEach(m => {
      router.removeRoute(m.name)
    })
    this.addMenus(router, menus)
  }
  addMenus(router: Router, menus: MenuData[]) {
    // 第一层是菜单
    menus.forEach(menuData => {
      const pagesData = menuData.list || []
      // 第二层是页面
      pagesData.forEach(pageData => {
        const _parent = new Set([menuData, pageData])
        if (this._menus.has(pageData.url)) {
          // 路由已经组册，加载路由
          const matchMenu = this._menus.get(pageData.url)
          const auths = pageData.list || []
          matchMenu.eachPage(page => {
            const route = {
              name: page.name,
              path: page.path,
              component: page.getComponent(),
              meta: {
                menus: _parent,
                tag: page.tag,
                auths: auths.map(i => i.perms).filter(i => i)
              },
              children: []
            }
            router.addRoute(route.name, route)
            this._loadedPages.set(page.name, page)
          })
        }
      })
    })
  }
}
